package cn.com.myshiro.shiro;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import cn.com.myshiro.bean.Syspermission;
import cn.com.myshiro.bean.Sysuser;
import cn.com.myshiro.dto.ActiveUserDto;
import cn.com.myshiro.service.SyspermissionService;
import cn.com.myshiro.service.SysuserService;



public class ShiroDbRealm extends AuthorizingRealm{
	
	private static Logger logger = LoggerFactory.getLogger(ShiroDbRealm.class);
	
	@Autowired
	SysuserService userservice;
	@Autowired
	SyspermissionService syspermissionservice;

	public ShiroDbRealm() {
		super();
	}
	
	/**
	 * 认证回调函数, 登录时调用.
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		logger.info(token.getUsername()+"---> 此username实际上是usercode");
		Sysuser user = new Sysuser();
		ActiveUserDto activeuser = new ActiveUserDto();
		List<Syspermission> ulist=null;
		List<Syspermission> tlist=null;
		try {
			//用户基本信息
			user = userservice.sysuserBycode(token.getUsername());
			//根据usercode查询菜单
			ulist=syspermissionservice.findMenuListByUserId(token.getUsername());
			//根据usercode查询url
			tlist=syspermissionservice.findPermissionListByUserId(token.getUsername());
		} catch (Exception e) {
			e.printStackTrace();
		}
		activeuser.setMenus(ulist);
		activeuser.setPermissions(tlist);
		activeuser.setUsercode(user.getUsercode());
		activeuser.setUserid(user.getId()+"");
		activeuser.setUsername(user.getUsername());
		System.out.println(activeuser);
		if (user != null && activeuser !=null) {
			return new SimpleAuthenticationInfo(activeuser, user.getPassword(), getName());
		}else{
			throw new AuthenticationException("用户名或密码错误请求拦截跳转到登陆页！");
		}
	}

	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		/* 这里编写授权代码 */
		//此处的user指的是上面放到SimpleAuthenticationInfo的第一个参数
		ActiveUserDto activeuser = (ActiveUserDto) principals.getPrimaryPrincipal();
		String usercode = activeuser.getUsercode();
		List<Syspermission> permissionlist = new ArrayList<Syspermission>();
		List<String> permissions = new ArrayList<String>();
		permissionlist=syspermissionservice.findPermissionListByUserId(usercode);
		//此处应该在数据库中查询
		for(Syspermission syspermission : permissionlist){
			permissions.add(syspermission.getPercode());
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
	    info.addStringPermissions(permissions);
		return info;
	}

	/**
	 * 更新用户授权信息缓存.
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清除所有用户授权信息缓存.
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}
	
	//清除缓存--此方法应该在 修改权限的service处调用
	public void clearCached() {
		PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
		super.clearCache(principals);
	}

}
